package com.xin.di.uav.user.order.service.impl;

import com.xin.di.uav.common.enums.ErrorEnum;
import com.xin.di.uav.common.enums.OrderTypeEnum;
import com.xin.di.uav.common.enums.PayStatusEnum;
import com.xin.di.uav.common.enums.RescueOrderStatusEnum;
import com.xin.di.uav.common.exception.BusinessException;
import com.xin.di.uav.common.request.order.BillAddRequest;
import com.xin.di.uav.common.utils.BeanUtil;
import com.xin.di.uav.mapper.BillMapper;
import com.xin.di.uav.po.Bill;
import com.xin.di.uav.po.OrderMapper;
import com.xin.di.uav.user.order.po.OrderPO;
import com.xin.di.uav.user.order.po.TaskStatusLog;
import com.xin.di.uav.user.order.service.CommonOrderService;
import com.xin.di.uav.user.order.service.ITaskStatusLogService;
import com.xin.di.uav.utils.WechatRefundUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Service
public class CommonOrderServiceImpl implements CommonOrderService {

    @Autowired
    private WechatRefundUtils wechatRefundUtils;


    @Autowired
    private OrderMapper orderInfoMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private ITaskStatusLogService iTaskStatusLogService;

    @Override
    public Date cancelOrder(String id) {
        Date date = new Date();
        OrderPO orderInfo = orderInfoMapper.selectById(id);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new BusinessException("订单不存在");
        }
        Integer orderStatus = orderInfo.getStatus();
        if (!orderStatus.equals(RescueOrderStatusEnum.TO_BE_PAID.getStatus()) && !orderStatus.equals(RescueOrderStatusEnum.WAITING_FOR_ORDER_ACCEPTANCE.getStatus())) {
            throw new BusinessException("不是待支付/等待平台接单/物资准备中状态");
        }
        if (orderStatus.equals(RescueOrderStatusEnum.WAITING_FOR_ORDER_ACCEPTANCE.getStatus())) {
            //1.查询是否退款过 2.退款 =》顺序不能调换
            String outRefundNo = orderInfo.getOutRefundNo();
            String refundId = orderInfo.getRefundId();
            BigDecimal totalAmount = orderInfo.getTotalAmount();
            if (ObjectUtils.isEmpty(outRefundNo) && ObjectUtils.isEmpty(refundId)) {
                //为空才是未退款
                WechatRefundUtils.CreateRequest request = new WechatRefundUtils.CreateRequest();
                request.transactionId = orderInfo.getTransactionId();
                request.outTradeNo = orderInfo.getOrderNo();
                request.outRefundNo = UUID.randomUUID().toString().replace("-", "");
                orderInfo.setOutRefundNo(request.outRefundNo);
                request.reason = "取消订单退款";
                request.notifyUrl = "https://cindyorder.com/uocs-rescue/" + "home/wx-pay/refund-notify";
                request.fundsAccount = WechatRefundUtils.ReqFundsAccount.AVAILABLE;
                request.amount = new WechatRefundUtils.AmountReq();
                request.amount.refund = totalAmount.multiply(BigDecimal.valueOf(100)).longValue();
                request.amount.total = request.amount.refund;
                request.amount.currency = "CNY";
                WechatRefundUtils.Refund refund = wechatRefundUtils.refund(request);
                if (!ObjectUtils.isEmpty(refund) && !ObjectUtils.isEmpty(refund.refundId)) {
                    orderInfo.setRefundId(refund.refundId);
                    //退款中，处理成功
                    BillAddRequest billAddRequest = new BillAddRequest();
                    billAddRequest.setOrderId(orderInfo.getId());
                    billAddRequest.setTcWaybillNo(orderInfo.getOrderNo());
                    billAddRequest.setPricePaid(orderInfo.getTotalAmount());
                    billAddRequest.setPayStatus(PayStatusEnum.REFUNDING.getValue());
                    billAddRequest.setUserId(orderInfo.getUserId());
                    billAddRequest.setType(OrderTypeEnum.REFUND.getValue());
                    billAddRequest.setOtherOrderNo(refund.refundId);
                    Bill bill = BeanUtil.copyProperties(billAddRequest, Bill.class);
                    billMapper.insert(bill);
                }
            }
        }
        TaskStatusLog taskStatusLog = new TaskStatusLog();

        if (orderStatus.equals(RescueOrderStatusEnum.TO_BE_PAID.getStatus())) {
            orderInfo.setStatus(RescueOrderStatusEnum.CANCEL_BEFORE_PAYMENT.getStatus());
            taskStatusLog.setStatus(RescueOrderStatusEnum.CANCEL_BEFORE_PAYMENT.getStatus());
        } else {
            orderInfo.setStatus(RescueOrderStatusEnum.CANCEL.getStatus());
            taskStatusLog.setStatus(RescueOrderStatusEnum.CANCEL.getStatus());
        }

        //恢复库存
        this.restoreInventory(orderInfo.getOrderNo());

        orderInfo.setUpdatedAt(date);
        orderInfoMapper.updateById(orderInfo);

        taskStatusLog.setTaskId(orderInfo.getId());
        taskStatusLog.setCreateTime(date);
        taskStatusLog.setUpdateTime(date);
        taskStatusLog.setUserId(orderInfo.getUserId());
        iTaskStatusLogService.addTaskStatusLog(taskStatusLog);
        return date;
    }

    @Override
    public void restoreInventory(String orderSn) {
//        //也可以指定锁时间的
//        //业务
//        Date date = new Date();
//        List<OrderCommodity> orderCommodities = orderCommodityRest.getByOrderSn(orderSn);
//        if (!CollectionUtils.isEmpty(orderCommodities)) {
//            List<String> commodityIds = orderCommodities.stream().map(orderCommodity -> orderCommodity.getCommodityId()).collect(Collectors.toList());
//            List<Product> commodities = commodityMapper.selectBatchIds(commodityIds);
//            orderCommodities.forEach(orderCommodity -> {
//                commodities.forEach(commodity -> {
//                    if (orderCommodity.getCommodityId().equals(commodity.getId())) {
//                        commodity.setStock(commodity.getStock() + orderCommodity.getCnt());
//                        commodity.setUpdatedAt(date);
//                        commodityMapper.updateById(commodity);
//                    }
//                });
//            });
//        }
    }
}
